package com.example.leo.mycharmingstudent.a0917.practice;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.leo.mycharmingstudent.R;
import com.example.leo.mycharmingstudent.a0905.ToastUtil;
import com.example.leo.mycharmingstudent.a0921.WebViewActivity;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Leo on 2020/9/17.
 */

public class MainPageFragment extends Fragment {

    private static final String TAG = "MainPageFragment";

    private ViewPager vpBanner;
    private RecyclerView rvArticle;

    @Nullable
    @Override
    public View onCreateView(
            @NonNull LayoutInflater inflater,
            @Nullable ViewGroup container,
            @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main_page, null, false);
        vpBanner = view.findViewById(R.id.vp_banner_fragment_main_page);
        rvArticle = view.findViewById(R.id.rv_article_fragment_main_page);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        requestBanner();
        requestArticle();
    }

    /**
     * 从网络获取文章列表
     * 接口：https://www.wanandroid.com/article/list/0/json
     * 请求方式GET
     */
    private void requestArticle() {
        OkHttpClient client = new OkHttpClient();
        Request.Builder builder = new Request.Builder();
        builder.url("https://www.wanandroid.com/article/list/0/json");
        Request request = builder.build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                ArticleEntity articleEntity = new Gson().fromJson(result, ArticleEntity.class);
                /*
                errorCode等于0，表示这次业务请求成功，DataBean里面会有数据
                如果不等于0，表示这次业务请求失败（有可能是参数错误之类的问题），DataBean一般为null

                请求成功与否的标识值，不一定为0.需要根据服务端定义来。
                 */
                if (articleEntity.getErrorCode() == 0) {
                    final List<ArticleEntity.DataBean.DatasBean> datas = articleEntity.getData().getDatas();
                    HandlerUtil.post(new Runnable() {
                        @Override
                        public void run() {
                            //不设置LayoutManager，界面不展示
                            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
                            rvArticle.setLayoutManager(linearLayoutManager);
                            ArticleAdapter articleAdapter = new ArticleAdapter(datas, getContext());
                            articleAdapter.setOnArticleItemClickListener(
                                    new ArticleAdapter.onArticleItemClickListener() {
                                @Override
                                public void onArticleItemClick(
                                        int position,
                                        ArticleEntity.DataBean.DatasBean datasBean) {
                                    ToastUtil.showToast(getContext(),datasBean.getLink());
                                    Intent intent = new Intent(getContext(), WebViewActivity.class);
                                    //Intent传递数据的大小有限制。不能传递过多的数据。
                                    intent.putExtra(WebViewActivity.URL,datasBean.getLink());
                                    startActivity(intent);
                                }
                            });
                            rvArticle.setAdapter(articleAdapter);
                        }
                    });
                }
            }
        });

    }

    /**
     * 从网络拿取广告图数据
     * 接口：https://www.wanandroid.com/banner/json
     * 请求方式GET
     */
    private void requestBanner() {
        OkHttpClient client = new OkHttpClient();
        Request.Builder builder = new Request.Builder();
        builder.url("https://www.wanandroid.com/banner/json");
        Request request = builder.build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            /**
             * 处理异常的两种方式：
             * 1.try-catch自己处理异常
             * 2.throw Exception  自己不处理，扔出去，谁爱处理谁处理
             * 如果都不处理会如何？app崩溃。
             * @param call
             * @param response
             * @throws IOException
             */
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.e(TAG, "onResponse: " + result);
                Gson gson = new Gson();
                final BannerEntity bannerEntity = gson.fromJson(result, BannerEntity.class);
                /*
                errorCode等于0，表示这次业务请求成功，DataBean里面会有数据
                如果不等于0，表示这次业务请求失败（有可能是参数错误之类的问题），DataBean一般为null

                请求成功与否的标识值，不一定为0.需要根据服务端定义来。
                 */
                if (bannerEntity.getErrorCode() == 0) {
                    Log.e(TAG, "onResponse: " + 0);
                    HandlerUtil.post(new Runnable() {
                        @Override
                        public void run() {
                            BannerAdapter bannerAdapter = new BannerAdapter(bannerEntity.getData(), getContext());
                            vpBanner.setAdapter(bannerAdapter);
                        }
                    });
                }
            }
        });
    }

}
